package com.lty.jeeg.server.modules.sys.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lty.jeeg.server.common.annotation.LogAnnotation;
import com.lty.jeeg.server.common.dto.ResponseInfo;
import com.lty.jeeg.server.common.enums.ResponseEnum;
import com.lty.jeeg.server.modules.sys.model.Dept;
import com.lty.jeeg.server.modules.sys.service.DeptService;
import com.lty.jeeg.server.common.utils.ResponseUtil;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.ApiOperation;

import java.util.List;

/**
 * @author : LTY
 * @date : 2018-12-05 09:42:50
 * Description :
 */
@Api(tags = "部门")
@RestController
@RequestMapping("/dept")
public class DeptController {

    private final DeptService deptService;

    @Autowired
    public DeptController(DeptService deptService) {
        this.deptService = deptService;
    }

    @LogAnnotation
    @PostMapping
    @ApiOperation(value = "部门保存")
    @RequiresPermissions("sys:dept:add")
    public ResponseInfo save(@RequestBody Dept dept) {
        return ResponseUtil.success(deptService.save(dept));
    }

    @GetMapping("getParent/{id}")
    @ApiOperation(value = "根据id获取上级部门")
    public ResponseInfo getParent(@PathVariable Long id) {
        Dept dept = deptService.getParentById(id);
        if (dept == null) {
            return ResponseUtil.error(ResponseEnum.DEPT_NOT_FOUND);
        }
        return ResponseUtil.success(dept);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取部门")
    public ResponseInfo get(@PathVariable Long id) {
        Dept dept = new Dept();
        if (id == 0) {
            dept.setId(id);
            return ResponseUtil.success(dept);
        }
        try {
            dept = deptService.getById(id);
        } catch (NullPointerException e) {
            return ResponseUtil.error(ResponseEnum.DEPT_NOT_FOUND);
        }
        return ResponseUtil.success(dept);
    }

    @LogAnnotation(module = "部门修改")
    @PutMapping
    @ApiOperation(value = "部门修改")
    @RequiresPermissions("sys:dept:edit")
    public ResponseInfo update(@RequestBody Dept dept) {
        return ResponseUtil.success(deptService.update(dept));
    }

    @GetMapping(value = {"", "list"})
    @ApiOperation(value = "部门列表")
    public ResponseInfo treeList() {
        List<Dept> deptList = deptService.treeList();
        List<Dept> list = Lists.newArrayList();
        setDeptList(0L, deptList, list);
        return ResponseUtil.success(list);
    }

    @GetMapping("tree")
    @ApiOperation(value = "部门树形列表for ZTree")
    public JSONArray listForZTree() {
        List<Dept> deptList = deptService.listAll();
        JSONArray array = new JSONArray();
        setDeptTree(0L, deptList, array);
        return array;
    }

    /**
     * 菜单树
     * 用于ZTREE展示
     * @param pId 父级节点ID
     * @param deptList 所有部门列表
     * @param array 树结构array
     */
    private void setDeptTree(Long pId, List<Dept> deptList, JSONArray array) {
        for (Dept dept : deptList) {
            if (dept.getParentId().equals(pId)) {
                String string = JSONObject.toJSONString(dept);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (deptList.stream().filter(p -> p.getParentId().equals(dept.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setDeptTree(dept.getId(), deptList, child);
                }
            }
        }
    }

    /**
     * 部门列表
     * 用于list页面展示
     * @param dId
     * @param deptList
     * @param list
     */
    private void setDeptList(Long dId, List<Dept> deptList, List<Dept> list) {
        for (Dept dept : deptList) {
            if (dept.getParentId().equals(dId)) {
                list.add(dept);
                if (deptList.stream().filter(p -> p.getParentId().equals(dept.getId())).findAny() != null) {
                    setDeptList(dept.getId(), deptList, list);
                }
            }
        }
    }

    @LogAnnotation
    @DeleteMapping("/{id}")
    @ApiOperation(value = "部门删除")
    public ResponseInfo delete(@PathVariable Long id) {

        ResponseEnum em = deptService.delete(id);
        if (em.getCode() == 0) {
            return ResponseUtil.success(em);
        } else {
            return ResponseUtil.error(em);
        }
    }
}
